#region

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using Mvc.Mailer;
using log4net;
using xConnected.Common.CategoryNew;
using xConnected.Common.Country;
using xConnected.Common.ExpertProfile;
using xConnected.Common.Language;
using xConnected.Core.Model;
using xConnected.Core.Model.ViewModel;
using xConnected.Infrastructure;
using xConnected.Mailers;
using xConnected.Service;

#endregion

namespace xConnected.Controllers
{
    public class ExpertProfileController : BaseController<ExpertProfile>
    {
        private readonly CategoryService _categoryService;
        private readonly CategorySkillService _categorySkillService;
        private readonly CountryService _countryService;
        private readonly EducationService _educationService;
        private readonly EducationSkillService _educationSkillService;
        private readonly IndustryService _industryService;
        private readonly LanguageService _languageService;
        private readonly LanguageSkillService _languageSkillService;
        private readonly ExpertProfileService _profileService;
        private readonly TechnologyService _technologyService;
        private readonly TechnologySkillService _technologySkillService;
        private readonly UserService _userService;


        public ExpertProfileController(ExpertProfileService profileService,
                                       EducationSkillService educationSkillService,
                                       EducationService educationService,
                                       CountryService countryService,
                                       LanguageSkillService languageSkillService,
                                       TechnologySkillService technologySkillService,
                                       TechnologyService technologyService,
                                       CategorySkillService categorySkillService,
                                       CategoryService categoryService,
                                       UserService userService,
                                       LanguageService languageService,
                                       IndustryService industryService)
        {
            _profileService = profileService;
            _educationSkillService = educationSkillService;
            _educationService = educationService;
            _countryService = countryService;
            _languageSkillService = languageSkillService;
            _technologySkillService = technologySkillService;
            _technologyService = technologyService;
            _categorySkillService = categorySkillService;
            _categoryService = categoryService;
            _userService = userService;
            _languageService = languageService;
            _industryService = industryService;
        }


        [HttpPost]
        public JsonResult ListAdvancedSearchAll(AdvancedSearchModelProfile profileModel)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                //if UserId is set to 1 it means method is called from MyProfiles mode, so set UserId to current user's id
                profileModel.UserId = profileModel.UserId == 1 ? user.Id : profileModel.UserId;

                var page = _profileService.AdvancedPagedSearchedAll(profileModel);
                var profiles = page.Entities.ToList().Select(p => new
                                                                      {
                                                                          p.Id,
                                                                          p.Created,
                                                                          p.Updated,
                                                                          p.Title,
                                                                          p.Description,
                                                                          p.Website,
                                                                          p.Skype,
                                                                          p.Facebook,
                                                                          p.Twitter,
                                                                          p.Linkedin,
                                                                          p.HourRate,
                                                                          p.DailyRate,
                                                                          p.MonthlyRate,
                                                                          p.AnnualRate,
                                                                          p.CommentRate,
                                                                          EmploymentType = p.JobType,
                                                                          EmploymentTypeText =
                                                                      Resources.ResourceManager.GetString(
                                                                          "JobType" + p.JobType.ToString(),
                                                                          Thread.CurrentThread.CurrentCulture),
                                                                          p.Experience,
                                                                          p.Availability,
                                                                          p.References,
                                                                          p.Other,
                                                                          ProfilePhoto = p.Photo,
                                                                          ProfilePhoto150X150 =
                                                                      p.Photo.Replace("/250X250_", "/150X150_"),
                                                                          ProfilePhoto80X80 =
                                                                      p.Photo.Replace("/250X250_", "/80X80_"),
                                                                          ProfilePhoto50X50 =
                                                                      p.Photo.Replace("/250X250_", "/50X0_"),
                                                                          p.Cv,
                                                                          p.Location,
                                                                          p.Email,
                                                                          p.PhoneNumber,
                                                                          p.IsDefault,
                                                                          p.AvailabilityStatus,
                                                                          AvailabilityStatusText =
                                                                      Resources.ResourceManager.GetString(
                                                                          "AvailabilityStatus" +
                                                                          p.AvailabilityStatus.ToString(),
                                                                          Thread.CurrentThread.CurrentCulture),
                                                                          CountryFlag =
                                                                      "../../Content/img/Flags/" +
                                                                      p.Country.ShortName.ToLower() + ".png",
                                                                          UserId = p.User.Id,
                                                                          EducationSkills =
                                                                      p.EducationSkills.Select(e => new
                                                                                                        {
                                                                                                            e.Id,
                                                                                                            e.
                                                                                                        Created,
                                                                                                            e.
                                                                                                        Updated,
                                                                                                            e.Program,
                                                                                                            e.University,
                                                                                                            e.BeginYear,
                                                                                                            e.EndYear,
                                                                                                            e.
                                                                                                        EducationId,
                                                                                                            EducationName
                                                                                                        =
                                                                                                        e.Education.
                                                                                                        Description
                                                                                                        }),
                                                                          Country = new
                                                                                        {
                                                                                            p.Country.Id,
                                                                                            p.Country.Created,
                                                                                            p.Country.Updated,
                                                                                            Description =
                                                                      CountryRes.ResourceManager.GetString(
                                                                          p.Country.Key,
                                                                          Thread.CurrentThread.CurrentCulture),
                                                                                            p.Country.ShortName
                                                                                        },
                                                                          Industry = new
                                                                                         {
                                                                                             p.Industry.Id,
                                                                                             p.Industry.Created,
                                                                                             p.Industry.Updated,
                                                                                             p.Industry.Description
                                                                                         },
                                                                          p.IndustryId,
                                                                          LanguageSkills =
                                                                      p.LanguageSkills.Select(l => new
                                                                                                       {
                                                                                                           l.Id,
                                                                                                           l.
                                                                                                       Created,
                                                                                                           l.
                                                                                                       Updated,
                                                                                                           l.
                                                                                                       Level,
                                                                                                           LevelText =
                                                                                                       Resources.
                                                                                                       ResourceManager.
                                                                                                       GetString(
                                                                                                           "Level" +
                                                                                                           l.Level.
                                                                                                               ToString(),
                                                                                                           Thread.
                                                                                                               CurrentThread
                                                                                                               .
                                                                                                               CurrentCulture),
                                                                                                           LanguageName
                                                                                                       =
                                                                                                       l.Language.
                                                                                                       Description,
                                                                                                           l.LanguageId
                                                                                                       }),
                                                                          TechnologySkills =
                                                                      p.TechnologySkills.Select(ts => new
                                                                                                          {
                                                                                                              ts.Id,
                                                                                                              ts.
                                                                                                          Created,
                                                                                                              ts.
                                                                                                          Updated,
                                                                                                              ts.
                                                                                                          Level,
                                                                                                              LevelText
                                                                                                          =
                                                                                                          Resources.
                                                                                                          ResourceManager
                                                                                                          .GetString(
                                                                                                              "Level" +
                                                                                                              ts.Level.
                                                                                                                  ToString
                                                                                                                  (),
                                                                                                              Thread.
                                                                                                                  CurrentThread
                                                                                                                  .
                                                                                                                  CurrentCulture),
                                                                                                              ts.
                                                                                                          Experience,
                                                                                                              ExperienceText
                                                                                                          =
                                                                                                          Resources.
                                                                                                          ResourceManager
                                                                                                          .GetString(
                                                                                                              "Experience" +
                                                                                                              ts.
                                                                                                                  Experience
                                                                                                                  .
                                                                                                                  ToString
                                                                                                                  (),
                                                                                                              Thread.
                                                                                                                  CurrentThread
                                                                                                                  .
                                                                                                                  CurrentCulture),
                                                                                                              ts.
                                                                                                          TechnologyId,
                                                                                                              TechnologyName
                                                                                                          =
                                                                                                          ts.Technology.
                                                                                                          Name
                                                                                                          }),
                                                                          CategorySkills =
                                                                      p.CategorySkills.Select(c => new
                                                                                                       {
                                                                                                           c.Id,
                                                                                                           c.
                                                                                                       Created,
                                                                                                           c.
                                                                                                       Updated,
                                                                                                           c.Level,
                                                                                                           LevelText =
                                                                                                       Resources.
                                                                                                       ResourceManager.
                                                                                                       GetString(
                                                                                                           "Level" +
                                                                                                           c.Level.
                                                                                                               ToString(),
                                                                                                           Thread.
                                                                                                               CurrentThread
                                                                                                               .
                                                                                                               CurrentCulture),
                                                                                                           c.Experience,
                                                                                                           ExperienceText
                                                                                                       =
                                                                                                       Resources.
                                                                                                       ResourceManager.
                                                                                                       GetString(
                                                                                                           "Experience" +
                                                                                                           c.Experience.
                                                                                                               ToString(),
                                                                                                           Thread.
                                                                                                               CurrentThread
                                                                                                               .
                                                                                                               CurrentCulture),
                                                                                                           CategoryName
                                                                                                       =
                                                                                                       c.Category.
                                                                                                       Description,
                                                                                                           c.CategoryId
                                                                                                       }),
                                                                          p.CountryId
                                                                      });

                return Json(new {page.Count, page.CurrentPage, page.PageSize, page.PagesCount, Entities = profiles},
                            JsonRequestBehavior.AllowGet);
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult ListAdvancedSearchSome(AdvancedSearchModelProfile profileModel)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                if (profileModel.UserId == 1)
                {
                    profileModel.UserId = _userService.GetUserByUsername(User.Identity.Name).Id;
                }
                var page = _profileService.AdvancedPagedSearchedSome(profileModel);
                var profiles = page.Entities.ToList().Select(p => new
                                                                      {
                                                                          p.Id,
                                                                          p.Created,
                                                                          p.Updated,
                                                                          p.Title,
                                                                          p.Description,
                                                                          p.Website,
                                                                          p.Skype,
                                                                          p.Facebook,
                                                                          p.Twitter,
                                                                          p.Linkedin,
                                                                          p.HourRate,
                                                                          p.DailyRate,
                                                                          p.MonthlyRate,
                                                                          p.AnnualRate,
                                                                          p.CommentRate,
                                                                          EmploymentType = p.JobType,
                                                                          EmploymentTypeText =
                                                                      Resources.ResourceManager.GetString(
                                                                          "JobType" + p.JobType.ToString(),
                                                                          Thread.CurrentThread.CurrentCulture),
                                                                          p.Experience,
                                                                          //    AbilitiesShort =
                                                                          //p.Experience.Substring(0, 170) + "...",
                                                                          p.Availability,
                                                                          p.References,
                                                                          p.Other,
                                                                          ProfilePhoto = p.Photo,
                                                                          p.Cv,
                                                                          p.Location,
                                                                          p.Email,
                                                                          p.PhoneNumber,
                                                                          p.IsDefault,
                                                                          p.AvailabilityStatus,
                                                                          AvailabilityStatusText =
                                                                      Resources.ResourceManager.GetString(
                                                                          "AvailabilityStatus" +
                                                                          p.AvailabilityStatus.ToString(),
                                                                          Thread.CurrentThread.CurrentCulture),
                                                                          CountryFlag =
                                                                      "../../Content/img/Flags/" +
                                                                      p.Country.ShortName.ToLower() + ".png",
                                                                          IsAuthenticated =
                                                                      _userService.GetUserByUsername(User.Identity.Name)
                                                                          .Id == p.UserId,
                                                                          UserId = p.User.Id,
                                                                          EducationSkills =
                                                                      p.EducationSkills.Select(e => new
                                                                                                        {
                                                                                                            e.Id,
                                                                                                            e.
                                                                                                        Created,
                                                                                                            e.
                                                                                                        Updated,
                                                                                                            e.Program,
                                                                                                            e.University,
                                                                                                            e.BeginYear,
                                                                                                            e.EndYear,
                                                                                                            e.
                                                                                                        EducationId,
                                                                                                            EducationName
                                                                                                        =
                                                                                                        e.Education.
                                                                                                        Description
                                                                                                        }),
                                                                          Country = new
                                                                                        {
                                                                                            p.Country.Id,
                                                                                            p.Country.Created,
                                                                                            p.Country.Updated,
                                                                                            Description =
                                                                      CountryRes.ResourceManager.GetString(
                                                                          p.Country.Key,
                                                                          Thread.CurrentThread.CurrentCulture),
                                                                                            p.Country.ShortName
                                                                                        },
                                                                          Industry = new
                                                                                         {
                                                                                             p.Industry.Id,
                                                                                             p.Industry.Created,
                                                                                             p.Industry.Updated,
                                                                                             p.Industry.Description
                                                                                         },
                                                                          p.IndustryId,
                                                                          LanguageSkills =
                                                                      p.LanguageSkills.Select(l => new
                                                                                                       {
                                                                                                           l.Id,
                                                                                                           l.
                                                                                                       Created,
                                                                                                           l.
                                                                                                       Updated,
                                                                                                           l.
                                                                                                       Level,
                                                                                                           LevelText =
                                                                                                       Resources.
                                                                                                       ResourceManager.
                                                                                                       GetString(
                                                                                                           "Level" +
                                                                                                           l.Level.
                                                                                                               ToString(),
                                                                                                           Thread.
                                                                                                               CurrentThread
                                                                                                               .
                                                                                                               CurrentCulture),
                                                                                                           LanguageName
                                                                                                       =
                                                                                                       l.Language.
                                                                                                       Description,
                                                                                                           l.LanguageId
                                                                                                       }),
                                                                          TechnologySkills =
                                                                      p.TechnologySkills.Select(ts => new
                                                                                                          {
                                                                                                              ts.Id,
                                                                                                              ts.
                                                                                                          Created,
                                                                                                              ts.
                                                                                                          Updated,
                                                                                                              ts.
                                                                                                          Level,
                                                                                                              LevelText
                                                                                                          =
                                                                                                          Resources.
                                                                                                          ResourceManager
                                                                                                          .GetString(
                                                                                                              "Level" +
                                                                                                              ts.Level.
                                                                                                                  ToString
                                                                                                                  (),
                                                                                                              Thread.
                                                                                                                  CurrentThread
                                                                                                                  .
                                                                                                                  CurrentCulture),
                                                                                                              ts.
                                                                                                          Experience,
                                                                                                              ExperienceText
                                                                                                          =
                                                                                                          Resources.
                                                                                                          ResourceManager
                                                                                                          .GetString(
                                                                                                              "Experience" +
                                                                                                              ts.
                                                                                                                  Experience
                                                                                                                  .
                                                                                                                  ToString
                                                                                                                  (),
                                                                                                              Thread.
                                                                                                                  CurrentThread
                                                                                                                  .
                                                                                                                  CurrentCulture),
                                                                                                              ts.
                                                                                                          TechnologyId,
                                                                                                              TechnologyName
                                                                                                          =
                                                                                                          ts.Technology.
                                                                                                          Name
                                                                                                          }),
                                                                          CategorySkills =
                                                                      p.CategorySkills.Select(c => new
                                                                                                       {
                                                                                                           c.Id,
                                                                                                           c.
                                                                                                       Created,
                                                                                                           c.
                                                                                                       Updated,
                                                                                                           c.Level,
                                                                                                           LevelText =
                                                                                                       Resources.
                                                                                                       ResourceManager.
                                                                                                       GetString(
                                                                                                           "Level" +
                                                                                                           c.Level.
                                                                                                               ToString(),
                                                                                                           Thread.
                                                                                                               CurrentThread
                                                                                                               .
                                                                                                               CurrentCulture),
                                                                                                           c.
                                                                                                       Experience,
                                                                                                           ExperienceText
                                                                                                       =
                                                                                                       Resources.
                                                                                                       ResourceManager.
                                                                                                       GetString(
                                                                                                           "Experience" +
                                                                                                           c.Experience.
                                                                                                               ToString(),
                                                                                                           Thread.
                                                                                                               CurrentThread
                                                                                                               .
                                                                                                               CurrentCulture),
                                                                                                           c.CategoryId,
                                                                                                           CategoryName
                                                                                                       =
                                                                                                       c.Category.
                                                                                                       Description
                                                                                                       }),
                                                                          p.CountryId
                                                                      });

                return Json(new {page.Count, page.CurrentPage, page.PageSize, page.PagesCount, Entities = profiles},
                            JsonRequestBehavior.AllowGet);
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJobTypes()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var jobTypes = new[]
                                   {
                                       new
                                           {
                                               Value = 0,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType0",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           },
                                       new
                                           {
                                               Value = 1,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType1",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           },
                                       new
                                           {
                                               Value = 2,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType2",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           },
                                       new
                                           {
                                               Value = 4,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType4",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           },
                                       new
                                           {
                                               Value = 8,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType8",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           },
                                       new
                                           {
                                               Value = 16,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType16",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           },
                                       new
                                           {
                                               Value = 32,
                                               Description =
                                           Resources.ResourceManager.GetString("EmploymentType32",
                                                                               Thread.CurrentThread.
                                                                                   CurrentCulture)
                                           }
                                   };

                return Json(jobTypes, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetLevels()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var levels = new[]
                                 {
                                     new
                                         {
                                             Value = 1,
                                             Description =
                                         Resources.ResourceManager.GetString("Basic",
                                                                             Thread.CurrentThread.CurrentCulture)
                                         },
                                     new
                                         {
                                             Value = 2,
                                             Description =
                                         Resources.ResourceManager.GetString("Intermediate",
                                                                             Thread.CurrentThread.CurrentCulture)
                                         },
                                     new
                                         {
                                             Value = 3,
                                             Description =
                                         Resources.ResourceManager.GetString("Advanced",
                                                                             Thread.CurrentThread.CurrentCulture)
                                         },
                                     new
                                         {
                                             Value = 4,
                                             Description =
                                         Resources.ResourceManager.GetString("Proficient",
                                                                             Thread.CurrentThread.CurrentCulture)
                                         },
                                     new
                                         {
                                             Value = 5,
                                             Description =
                                         Resources.ResourceManager.GetString("Professional",
                                                                             Thread.CurrentThread.CurrentCulture)
                                         }
                                 };

                return Json(levels, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetExperiences()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var experiences = new[]
                                      {
                                          new
                                              {
                                                  Value = 1,
                                                  Description =
                                              Resources.ResourceManager.GetString("LessThan1Year",
                                                                                  Thread.CurrentThread.CurrentCulture)
                                              },
                                          new
                                              {
                                                  Value = 2,
                                                  Description =
                                              Resources.ResourceManager.GetString("OneToThreeYears",
                                                                                  Thread.CurrentThread.CurrentCulture)
                                              },
                                          new
                                              {
                                                  Value = 3,
                                                  Description =
                                              Resources.ResourceManager.GetString("ThreeToFiveYears",
                                                                                  Thread.CurrentThread.CurrentCulture)
                                              },
                                          new
                                              {
                                                  Value = 4,
                                                  Description =
                                              Resources.ResourceManager.GetString("FiveToTenYears",
                                                                                  Thread.CurrentThread.CurrentCulture)
                                              },
                                          new
                                              {
                                                  Value = 5,
                                                  Description =
                                              Resources.ResourceManager.GetString("MoreThenTenYears",
                                                                                  Thread.CurrentThread.CurrentCulture)
                                              }
                                      };

                return Json(experiences, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetAvailabilityStatus()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var availabilityStatus = new[]
                                             {
                                                 new
                                                     {
                                                         Value = 1,
                                                         Description =
                                                     Resources.ResourceManager.GetString("AvailabilityStatus1",
                                                                                         Thread.CurrentThread.
                                                                                             CurrentCulture)
                                                     },
                                                 new
                                                     {
                                                         Value = 2,
                                                         Description =
                                                     Resources.ResourceManager.GetString("AvailabilityStatus2",
                                                                                         Thread.CurrentThread.
                                                                                             CurrentCulture)
                                                     },
                                                 new
                                                     {
                                                         Value = 3,
                                                         Description =
                                                     Resources.ResourceManager.GetString("AvailabilityStatus3",
                                                                                         Thread.CurrentThread.
                                                                                             CurrentCulture)
                                                     }
                                             };

                return Json(availabilityStatus, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJsonEducation()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var educations = _educationService.GetAll().ToList().Select(e => new
                                                                                     {
                                                                                         e.Id,
                                                                                         e.Created,
                                                                                         e.Updated,
                                                                                         e.Key,
                                                                                         e.Description,
                                                                                         //    Description =
                                                                                         //EducationRes.ResourceManager.
                                                                                         //GetString(e.Key,
                                                                                         //          Thread.CurrentThread.
                                                                                         //              CurrentCulture),
                                                                                         e.Title
                                                                                     });
                return Json(educations, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }


        public JsonResult GetJsonCountry()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var countries = _countryService.GetAll().ToList().OrderBy(c => CountryRes.ResourceManager.GetString(
                    c.Key,
                    Thread.CurrentThread.CurrentCulture)).Select(c => new
                                                                          {
                                                                              c.Id,
                                                                              c.
                                                                          Created,
                                                                              c.
                                                                          Updated,
                                                                              c.
                                                                          ShortName,
                                                                              c.Key,
                                                                              Description
                                                                          =
                                                                          CountryRes
                                                                          .
                                                                          ResourceManager
                                                                          .GetString
                                                                          (
                                                                              c.Key,
                                                                              Thread
                                                                                  .
                                                                                  CurrentThread
                                                                                  .
                                                                                  CurrentCulture)
                                                                          });
                return Json(countries, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }


        public JsonResult GetJsonLanguageSkill()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var languageSkills = _languageSkillService.GetAll().Select(l => new
                                                                                    {
                                                                                        l.Id,
                                                                                        l.Created,
                                                                                        l.Updated,
                                                                                        l.Level,
                                                                                        LanguageName =
                                                                                    l.Language.Description,
                                                                                        l.LanguageId
                                                                                    });
                return Json(languageSkills, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJsonLanguages()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var languages = _languageService.GetAll().ToList().OrderBy(l => LanguageRes.ResourceManager.GetString(
                    l.Key,
                    Thread.CurrentThread.CurrentCulture)).Select(l => new
                                                                          {
                                                                              l.Id,
                                                                              l.Created,
                                                                              l.Updated,
                                                                              l.Description,
                                                                              l.Key,
                                                                              l.ShortName
                                                                          });
                return Json(languages, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJsonTechnologies()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var technologies = _technologyService.GetAll().OrderBy(t => t.Name).Select(l => new
                                                                                                    {
                                                                                                        l.Id,
                                                                                                        l.Created,
                                                                                                        l.Updated,
                                                                                                        l.Name
                                                                                                    });
                return Json(technologies, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJsonTechnologiesNames()
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var technologies = _technologyService.GetAll().OrderBy(t => t.Name);
                var technologiesNames = new List<string>();
                technologies.ToList().ForEach(t => technologiesNames.Add(t.Name));
                return Json(technologiesNames, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetChildCategories(Category category)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var categories =
                    _categoryService.GetAll().ToList().Where(
                        c => (category.Id > 0 ? c.ParentCategoryId == category.Id : c.ParentCategory == null)).Select(
                            c => new
                                     {
                                         c.Id,
                                         c.Created,
                                         c.Updated,
                                         Description =
                                     CategoryNew.ResourceManager.GetString(c.Key, Thread.CurrentThread.CurrentCulture),
                                         c.Key,
                                         IsLeaf = c.ChildCategories.Count == 0
                                     });
                return Json(categories, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public ActionResult ContactFreelancer(int id, ContactModel model)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var mailer = new UserMailer(_userService);
                var msg = mailer.Contact(id, model);
                msg.Send();
                return Content("Ok");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Content(ex.Message);
            }
        }

        [HttpPost]
        public JsonResult Save(ExpertProfile profile)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                profile.User = user;

                //set profile as default if it's first user's profile
                if(user.ExpertProfiles.Count == 0 && user.CompanyProfiles.Count == 0)
                {
                    profile.IsDefault = true;
                }

                var selectedLanguageSkills = new List<LanguageSkill>(profile.LanguageSkills);
                profile.LanguageSkills.Clear();
                var selectedTechnologySkills = new List<TechnologySkill>(profile.TechnologySkills);
                profile.TechnologySkills.Clear();
                var selectedEducationSkills = new List<EducationSkill>(profile.EducationSkills);
                profile.EducationSkills.Clear();
                var selectedCategorySkills = new List<CategorySkill>(profile.CategorySkills);
                profile.CategorySkills.Clear();
                profile.Country = null;

                // first save the parent entity in order to autogenerate his Id
                _profileService.SaveOrUpdate(profile);

                //create directories for the new profile
                var di1 =
                    new DirectoryInfo(
                        Server.MapPath("~/Content/Uploads/" +
                                       Path.Combine(user.Username, "ExpertProfiles", profile.Id.ToString(), "Photo")));
                di1.Create();

                var di2 =
                    new DirectoryInfo(
                        Server.MapPath("~/Content/Uploads/" +
                                       Path.Combine(user.Username, "ExpertProfiles", profile.Id.ToString(), "Cv")));
                di2.Create();

                //Save Photo
                var username = _userService.GetUserByUsername(User.Identity.Name).Username;
                var fileNamePhoto = profile.Photo.Substring(profile.Photo.IndexOf("/250X250_") + 9);
                var directoryPhoto =
                    Server.MapPath("~/Content/Uploads/" +
                                   Path.Combine(username, "ExpertProfiles", profile.Id.ToString(), "Photo"));

                var dirPhoto = new DirectoryInfo(directoryPhoto);
                if (!dirPhoto.Exists)
                    dirPhoto.Create();
                foreach (var fi in dirPhoto.GetFiles())
                {
                    if (!fi.FullName.Contains("\\250X250_" + fileNamePhoto) &&
                        !fi.FullName.Contains("\\150X150_" + fileNamePhoto) &&
                        !fi.FullName.Contains("\\80X80_" + fileNamePhoto))
                    {
                        fi.Delete();
                    }
                }

                //Save Cv
                var fileNameCv = profile.Cv.Substring(profile.Cv.IndexOf("/Cv_") + 4);
                var directoryCv =
                    Server.MapPath("~/Content/Uploads/" +
                                   Path.Combine(username, "ExpertProfiles", profile.Id.ToString(), "Cv"));

                var dirCv = new DirectoryInfo(directoryCv);
                if (!dirCv.Exists)
                    dirCv.Create();
                foreach (var fi in dirCv.GetFiles())
                {
                    if (!fi.FullName.Contains("\\Cv_" + fileNameCv))
                    {
                        fi.Delete();
                    }
                }
                // then set this Id to all his child relationships foreign key properties
                profile.LanguageSkills = new List<LanguageSkill>(selectedLanguageSkills);
                profile.LanguageSkills.ToList().ForEach(l => l.ExpertProfileId = profile.Id);
                profile.TechnologySkills = new List<TechnologySkill>(selectedTechnologySkills);
                profile.TechnologySkills.ToList().ForEach(t => t.ExpertProfileId = profile.Id);
                profile.CategorySkills = new List<CategorySkill>(selectedCategorySkills);
                profile.CategorySkills.ToList().ForEach(c => c.ExpertProfileId = profile.Id);
                profile.EducationSkills = new List<EducationSkill>(selectedEducationSkills);
                profile.EducationSkills.ToList().ForEach(e => e.ExpertProfileId = profile.Id);

                foreach (var languageSkill in profile.LanguageSkills)
                {
                    languageSkill.ExpertProfileId = profile.Id;
                }
                foreach (var technologySkill in profile.TechnologySkills)
                {
                    technologySkill.ExpertProfileId = profile.Id;
                }
                foreach (var categorySkill in profile.CategorySkills)
                {
                    categorySkill.ExpertProfileId = profile.Id;
                }
                foreach (var educationSkill in profile.EducationSkills)
                {
                    educationSkill.ExpertProfileId = profile.Id;
                }
                _profileService.SaveOrUpdate(profile);

                return Json(profile.Id, JsonRequestBehavior.AllowGet);
            }

            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult Update(ExpertProfile profile)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                profile.User = user;
                //if the profile belongs to current user save changes
                if (profile.UserId == user.Id)
                {
                    var oldProfile = _profileService.GetById(profile.Id);

                    // load the old entity from the DB and manually set all its new property values
                    oldProfile.Title = profile.Title;
                    oldProfile.Description = profile.Description;
                    oldProfile.Website = profile.Website;
                    oldProfile.Skype = profile.Skype;
                    oldProfile.Facebook = profile.Facebook;
                    oldProfile.Twitter = profile.Twitter;
                    oldProfile.Linkedin = profile.Linkedin;
                    oldProfile.HourRate = profile.HourRate;
                    oldProfile.DailyRate = profile.DailyRate;
                    oldProfile.MonthlyRate = profile.MonthlyRate;
                    oldProfile.AnnualRate = profile.AnnualRate;
                    oldProfile.CommentRate = profile.CommentRate;
                    oldProfile.JobType = profile.JobType;
                    oldProfile.Experience = profile.Experience;
                    oldProfile.References = profile.References;
                    oldProfile.Availability = profile.Availability;
                    oldProfile.Other = profile.Other;
                    oldProfile.Location = profile.Location;
                    oldProfile.Email = profile.Email;
                    oldProfile.PhoneNumber = profile.PhoneNumber;
                    oldProfile.CountryId = profile.CountryId;

                    //Save Photo
                    var username = _userService.GetUserByUsername(User.Identity.Name).Username;
                    var fileNamePhoto = profile.Photo.Substring(profile.Photo.IndexOf("/250X250_") + 9);
                    var directoryPhoto =
                        Server.MapPath("~/Content/Uploads/" +
                                       Path.Combine(username, "ExpertProfiles", profile.Id.ToString(), "Photo"));

                    var dirPhoto = new DirectoryInfo(directoryPhoto);
                    if (!dirPhoto.Exists)
                        dirPhoto.Create();
                    foreach (var fi in dirPhoto.GetFiles())
                    {
                        if (!fi.FullName.Contains("\\250X250_" + fileNamePhoto) &&
                            !fi.FullName.Contains("\\150X150_" + fileNamePhoto) &&
                            !fi.FullName.Contains("\\80X80_" + fileNamePhoto))
                        {
                            fi.Delete();
                        }
                    }

                    oldProfile.Photo = profile.Photo;

                    //Save Cv
                    var fileNameCv = profile.Cv.Substring(profile.Cv.IndexOf("/Cv_") + 4);
                    var directoryCv =
                        Server.MapPath("~/Content/Uploads/" +
                                       Path.Combine(username, "ExpertProfiles", profile.Id.ToString(), "Cv"));

                    var dirCv = new DirectoryInfo(directoryCv);
                    if (!dirCv.Exists)
                        dirCv.Create();
                    foreach (var fi in dirCv.GetFiles())
                    {
                        if (!fi.FullName.Contains("\\Cv_" + fileNameCv))
                        {
                            fi.Delete();
                        }
                    }

                    oldProfile.Cv = profile.Cv;

                    // load all the new relationships from the DB
                    // listID = {1, 2, 5, 7}
                    // LS = [{Id = 1, Text = , ...}, {}
                    // select * from LS l where In (select LS.* from PP Inner join LS on PP.Id = LS.ExpertProfileId WHERE PP.ID = 3)

                    profile.LanguageSkills.ToList().ForEach(l => l.ExpertProfileId = profile.Id);

                    var lSkills = _languageSkillService.GetAll().Where(ls => ls.ExpertProfileId == oldProfile.Id);
                    lSkills.ToList().ForEach(ls => _languageSkillService.Delete(ls));

                    profile.TechnologySkills.ToList().ForEach(t => t.ExpertProfileId = profile.Id);

                    var tSkills = _technologySkillService.GetAll().Where(ts => ts.ExpertProfileId == oldProfile.Id);
                    tSkills.ToList().ForEach(ts => _technologySkillService.Delete(ts));


                    profile.CategorySkills.ToList().ForEach(l => l.ExpertProfileId = profile.Id);

                    var cSkills = _categorySkillService.GetAll().Where(cs => cs.ExpertProfileId == oldProfile.Id);
                    cSkills.ToList().ForEach(cs => _categorySkillService.Delete(cs));

                    profile.EducationSkills.ToList().ForEach(t => t.ExpertProfileId = profile.Id);

                    var eSkills = _educationSkillService.GetAll().Where(es => es.ExpertProfileId == oldProfile.Id);
                    eSkills.ToList().ForEach(es => _educationSkillService.Delete(es));

                    // clean the old relationships and set the new ones
                    oldProfile.LanguageSkills.Clear();
                    oldProfile.TechnologySkills.Clear();
                    oldProfile.EducationSkills.Clear();
                    //oldProfile.Country = null;
                    oldProfile.CategorySkills.Clear();

                    _profileService.SaveOrUpdate(oldProfile);

                    // language skills and technology skills require also to set their foreign key because they are "one to many" relationship
                    // for the "many to many" it is enough to add it to the list

                    profile.TechnologySkills.ToList().ForEach(l => oldProfile.TechnologySkills.Add(l));
                    profile.LanguageSkills.ToList().ForEach(l => oldProfile.LanguageSkills.Add(l));
                    profile.CategorySkills.ToList().ForEach(l => oldProfile.CategorySkills.Add(l));
                    profile.EducationSkills.ToList().ForEach(l => oldProfile.EducationSkills.Add(l));

                    //educations.ForEach(l => oldProfile.EducationSkills.Add(l));
                    //categories.ForEach(l => oldProfile.CategorySkills.Add(l));

                    _profileService.SaveOrUpdate(oldProfile);

                    return Json(profile.Id, JsonRequestBehavior.AllowGet);
                }
                //else if the profile doesn't belong to current user return "error" which means to render "you are not allowed...." message on client side
                return Json("ERROR", JsonRequestBehavior.AllowGet);
            }

            catch (Exception ex)
            {
                //log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult DeleteMesExpertUser(int profileId)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var profile = _profileService.GetById(profileId);
                _profileService.Delete(profile);
                return Json("OK", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }


        public JsonResult CreateTechnology(string technologyName)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                if (_technologyService.GetAll().All(t => t.Name != technologyName))
                {
                    var newTech = new Technology {Name = technologyName};
                    _technologyService.SaveOrUpdate(newTech);

                    var technologyArray = new List<Technology>();
                    technologyArray.Add(newTech);
                    return Json(technologyArray, JsonRequestBehavior.AllowGet);
                }

                var existingTech = _technologyService.GetAll().First(t => t.Name == technologyName);
                var existingTechnologyArray = new List<Technology>();
                existingTechnologyArray.Add(existingTech);
                return Json(existingTechnologyArray, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public ActionResult CheckSignedIn(int ExpertProfileId)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var user = _userService.GetUserByUsername(User.Identity.Name);
                var profileIds = user.ExpertProfiles.Select(p => p.Id);

                //if user is signed in and the current profile belongs to that user
                if (user != null && profileIds.Contains(ExpertProfileId))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Content("ERROR");
            }
        }

        public JsonResult GetKeywordsAutocomplete(string searchTerm = "", int maxRows = 8)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var countries = _countryService.GetAll().Select(l => new
                                                                         {
                                                                             l.Description,
                                                                             l.Id,
                                                                             Type = "co"
                                                                         });
                var industries = _industryService.GetAll().Select(l => new
                                                                           {
                                                                               l.Description,
                                                                               l.Id,
                                                                               Type = "in"
                                                                           });
                var categories = _categoryService.GetAll().Select(l => new
                                                                           {
                                                                               l.Description,
                                                                               l.Id,
                                                                               Type = "ca"
                                                                           });
                var technologies = _technologyService.GetAll().Select(l => new
                                                                               {
                                                                                   Description = l.Name,
                                                                                   l.Id,
                                                                                   Type = "te"
                                                                               });
                var educations = _educationService.GetAll().Select(l => new
                                                                            {
                                                                                l.Description,
                                                                                l.Id,
                                                                                Type = "ed"
                                                                            });
                var languages = _languageService.GetAll().Select(l => new
                                                                          {
                                                                              l.Description,
                                                                              l.Id,
                                                                              Type = "la"
                                                                          });
                var keywords =
                    countries.Union(industries).Union(categories).Union(technologies).Union(educations).Union(languages);
                if (searchTerm != "")
                {
                    keywords =
                        keywords.Where(l => l.Description.ToLower().Contains(searchTerm.ToLower())).Take(maxRows);
                }
                return Json(keywords, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJobTypesAutocomplete(string searchTerm = "", int maxRows = 8)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                //var employmentType0 = new EmploymentAvailability
                //{
                //    Value = 0,
                //    Description =
                //        Resources.ResourceManager.GetString("EmploymentType0",
                //                                            Thread.CurrentThread.
                //                                                CurrentCulture)
                //};
                var employmentType1 = new EmploymentAvailability
                                          {
                                              Value = 1,
                                              Description =
                                                  Resources.ResourceManager.GetString("EmploymentType1",
                                                                                      Thread.CurrentThread.
                                                                                          CurrentCulture)
                                          };
                var employmentType2 = new EmploymentAvailability
                                          {
                                              Value = 2,
                                              Description =
                                                  Resources.ResourceManager.GetString("EmploymentType2",
                                                                                      Thread.CurrentThread.
                                                                                          CurrentCulture)
                                          };
                var employmentType4 = new EmploymentAvailability
                                          {
                                              Value = 4,
                                              Description =
                                                  Resources.ResourceManager.GetString("EmploymentType4",
                                                                                      Thread.CurrentThread.
                                                                                          CurrentCulture)
                                          };
                var employmentType8 = new EmploymentAvailability
                                          {
                                              Value = 8,
                                              Description =
                                                  Resources.ResourceManager.GetString("EmploymentType8",
                                                                                      Thread.CurrentThread.
                                                                                          CurrentCulture)
                                          };
                var employmentType16 = new EmploymentAvailability
                                           {
                                               Value = 16,
                                               Description =
                                                   Resources.ResourceManager.GetString("EmploymentType16",
                                                                                       Thread.CurrentThread.
                                                                                           CurrentCulture)
                                           };
                var employmentType32 = new EmploymentAvailability
                                           {
                                               Value = 8,
                                               Description =
                                                   Resources.ResourceManager.GetString("EmploymentType32",
                                                                                       Thread.CurrentThread.
                                                                                           CurrentCulture)
                                           };
                var employmentTypes = new List<EmploymentAvailability>
                                          {
                                              employmentType1,
                                              employmentType2,
                                              employmentType4,
                                              employmentType8,
                                              employmentType16,
                                              employmentType32
                                          };
                if (searchTerm != "")
                {
                    employmentTypes =
                        employmentTypes.Where(e => e.Description.ToLower().Contains(searchTerm.ToLower())).ToList();
                }

                return Json(employmentTypes, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetAvailabilityStatusesAutocomplete(string searchTerm = "", int maxRows = 8)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var availabilityStatus1 = new EmploymentAvailability
                                              {
                                                  Value = 1,
                                                  Description =
                                                      Resources.ResourceManager.GetString("AvailabilityStatus1",
                                                                                          Thread.CurrentThread.
                                                                                              CurrentCulture)
                                              };
                var availabilityStatus2 = new EmploymentAvailability
                                              {
                                                  Value = 2,
                                                  Description =
                                                      Resources.ResourceManager.GetString("AvailabilityStatus2",
                                                                                          Thread.CurrentThread.
                                                                                              CurrentCulture)
                                              };
                var availabilityStatus3 = new EmploymentAvailability
                                              {
                                                  Value = 3,
                                                  Description =
                                                      Resources.ResourceManager.GetString("AvailabilityStatus3",
                                                                                          Thread.CurrentThread.
                                                                                              CurrentCulture)
                                              };

                var availabilityStatuses = new List<EmploymentAvailability>
                                               {
                                                   availabilityStatus1,
                                                   availabilityStatus2,
                                                   availabilityStatus3
                                               };
                if (searchTerm != "")
                {
                    availabilityStatuses =
                        availabilityStatuses.Where(e => e.Description.ToLower().Contains(searchTerm.ToLower())).ToList();
                }

                return Json(availabilityStatuses, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult SetAsDefault(ExpertProfile expertProfile)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var profile = _profileService.GetById(expertProfile.Id);
                var user = profile.User;
                //set isdefault=false to all other profiles that belong to current user
                user.ExpertProfiles.ToList().ForEach(e => e.IsDefault = false);
                user.CompanyProfiles.ToList().ForEach(c => c.IsDefault = false);
                foreach (var company in user.CompanyProfiles)
                {
                    foreach (var project in company.Positions)
                    {
                        project.IsDefault = false;
                    }
                }

                profile.IsDefault = true;
                _profileService.SaveOrUpdate(profile);
                return Json("OK", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new { Result = "ERROR", ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}